//
//  MineVC.swift
//  kxf
//
//  Created by Mac on 2024/3/5.
//

import Foundation
import MCToast

class MineVC: WHBaseViewVC {
    
    override func viewWillAppear(_ animated: Bool) {
        sendUserCenterRequest()
        sendGetSampleImgRequest()
        sendDataQueryRequest()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        initUI()
        sendGetVersionRequest()
        NotificationCenter.default.addObserver(self, selector: #selector(refreshUI), name: NSNotification.Name(rawValue: "refreshUserInfo"), object: nil)
    }
    lazy var topVm : MineTopVM = {
        let vm = MineTopVM.init(frame: .zero)
        vm.authenTapBlock = {()in
            if UserModel.shared.posStatus == "-4" || UserModel.shared.posStatus == "-3" || UserModel.shared.posStatus == "-2" || UserModel.shared.posStatus == "-1"{
                self.presentAlertVc(confirmBtn: "去修改", message: "", title: "\(UserModel.shared.failResult)", cancelBtn: "暂不处理", handler: { action in
                    self.sendAuthenMsgVerifyRequest()
                }, viewController: self)
            }else if UserModel.shared.posStatus == "0"{
                self.sendAuthenMsgVerifyRequest()
//                let vc = AuthenTypeVC()
//                vc.isFromMine = true
//                self.navigationController?.pushViewController(vc, animated: true)
            }else if UserModel.shared.posStatus == "1"{
                MCToast.mc_text("审核中，请耐心等待...")
            }else if UserModel.shared.posStatus == "2" || UserModel.shared.posStatus == "3"{
                if UserModel.shared.signType != "" && UserModel.shared.signType != "1" && UserModel.shared.signType != "0"{
                    self.openUrl(urlString: UserModel.shared.signType)
                }else{
                    let vc = AuthoriVC()
                    vc.phone = UserModel.shared.phone
                    self.navigationController?.pushViewController(vc, animated: true)
                }
            }else if UserModel.shared.posStatus == "4"{
                self.sendAuthenMsgVerifyRequest()
            }
        }
        return vm
    }()
    lazy var funcVm : MineFuncVM = {
        let vm = MineFuncVM.init(frame: CGRect.init(x: 0, y: self.topVm.frame.maxY-MineFuncItemVM().selfHeight*0.5, width: 0, height: 0))
        vm.qrCodeVm.tapBlock = {()in
//            if UserModel.shared.posStatus == "3"{
                if UserModel.shared.sn.count > 0{
                    let vc = MyQrCodeVC()
                    self.navigationController?.pushViewController(vc, animated: true)
                }else{
                    let vc = BindSNVC()
                    self.navigationController?.pushViewController(vc, animated: true)
                }
//            }else{
//                self.presentAlertVcNoAction(title: "请先完成商户入网审核流程！", viewController: self)
//            }
        }
        vm.mercMsgVm.tapBlock = {()in
            self.sendAuthenMsgVerifyRequest()
        }
        vm.bankCardVm.tapBlock = {()in
            if UserModel.shared.posStatus == "2" || UserModel.shared.posStatus == "3" || UserModel.shared.posStatus == "4"{
                let vc = BankCardVC()
                self.navigationController?.pushViewController(vc, animated: true)
            }else{
                self.presentAlertVcNoAction(title: "请先完成商户入网审核流程！", viewController: self)
            }
        }
        vm.mercManageVm.tapBlock = {()in
            let vc = MarketManageVC()
            self.navigationController?.pushViewController(vc, animated: true)
        }
        vm.settingVm.tapBlock = {()in
            let vc = SettingVC()
            self.navigationController?.pushViewController(vc, animated: true)
        }
        vm.helpCenterVm.tapBlock = {()in
            let vc = ServiceVC()
            self.navigationController?.pushViewController(vc, animated: true)
        }
        vm.settleVm.tapBlock = {()in
            if UserModel.shared.posStatus == "2" || UserModel.shared.posStatus == "3" || UserModel.shared.posStatus == "4"{
                let vc = SettleListVC()
                self.navigationController?.pushViewController(vc, animated: true)
            }else{
                self.presentAlertVcNoAction(title: "请先完成商户入网审核流程！", viewController: self)
            }
        }
        vm.tradeRecordsVm.tapBlock = {()in
            let vc = TradeListVC()
            self.navigationController?.pushViewController(vc, animated: true)
        }
        vm.authoriVm.tapBlock = {()in
            let vc = AuthoriVC()
            vc.phone = UserModel.shared.phone
            self.navigationController?.pushViewController(vc, animated: true)
        }
        vm.signVm.tapBlock = {()in
            self.openUrl(urlString: UserModel.shared.signType)
        }
        vm.mercFeeVm.tapBlock = {()in
            if UserModel.shared.posStatus == "2" || UserModel.shared.posStatus == "3" || UserModel.shared.posStatus == "4"{
                let vc = SetRateVC()
                vc.isMerc = true
                vc.phone = UserModel.shared.phone
                self.navigationController?.pushViewController(vc, animated: true)
            }else{
                self.presentAlertVcNoAction(title: "请先完成商户入网审核流程！", viewController: self)
            }
        }
        
        return vm
    }()
    lazy var funcVmNew : MineFuncVMNew = {
        let vm = MineFuncVMNew.init(frame: CGRect.init(x: 0, y: self.topVm.frame.maxY-kFitWidth(45), width: 0, height: 0))
        vm.tapBlock = {(type)in
            switch type {
            case .tools:
                let vc = DeviceTypeListVC()
                self.navigationController?.pushViewController(vc, animated: true)
                break
            case .merc_msg:
                self.sendAuthenMsgVerifyRequest()
            case .bankcard:
                if UserModel.shared.posStatus == "2" || UserModel.shared.posStatus == "3" || UserModel.shared.posStatus == "4"{
                    let vc = BankCardVC()
                    self.navigationController?.pushViewController(vc, animated: true)
                }else{
                    self.presentAlertVcNoAction(title: "请先完成商户入网审核流程！", viewController: self)
                }
            case .trade_detail:
                let vc = TradeListVC()
                self.navigationController?.pushViewController(vc, animated: true)
            case .help_center:
                let vc = ServiceVC()
                self.navigationController?.pushViewController(vc, animated: true)
            case .setting:
                let vc = SettingVC()
                self.navigationController?.pushViewController(vc, animated: true)
            case .merc_manage:
                let vc = MarketManageVC()
                self.navigationController?.pushViewController(vc, animated: true)
            case .authori:
                let vc = AuthoriVC()
                vc.phone = UserModel.shared.phone
                self.navigationController?.pushViewController(vc, animated: true)
            case .merc_fee:
                if UserModel.shared.posStatus == "2" || UserModel.shared.posStatus == "3" || UserModel.shared.posStatus == "4"{
                    let vc = SetRateVC()
                    vc.isMerc = true
                    vc.phone = UserModel.shared.phone
                    self.navigationController?.pushViewController(vc, animated: true)
                }else{
                    self.presentAlertVcNoAction(title: "请先完成商户入网审核流程！", viewController: self)
                }
            case .merc_sign:
                self.openUrl(urlString: UserModel.shared.signType)
                
            case .settle_manage:
                self.presentAlertVcNoAction(title: "结算管理", viewController: self)
            }
        }
        return vm
    }()
}

extension MineVC{
    func initUI() {
        view.addSubview(scrollView)
        scrollView.addSubview(topVm)
//        scrollView.addSubview(funcVm)
        scrollView.addSubview(funcVmNew)
        
        scrollView.contentSize = CGSize.init(width: 0, height: self.funcVmNew.frame.maxY + getTabbarHeight()+kFitWidth(20))
    }
    @objc func refreshUI() {
        topVm.updateUI()
//        funcVm.refreshUI()
        funcVmNew.updateUI()
        scrollView.contentSize = CGSize.init(width: 0, height: self.funcVmNew.frame.minY + self.funcVmNew.selfHeight + getTabbarHeight()+kFitWidth(20))
    }
}

extension MineVC{
    func sendAuthenMsgVerifyRequest() {
        let urlString = "\(URL_authen_msg_verify)?tel=\(UserModel.shared.phone)"
        WHNetworkUtil.shareManager().GET(urlString: urlString,vc:self) { response in
            DLLog(message: "\(response)")
            if response["code"]as? Int ?? -1 == 200{
                let data = response["data"]as? NSDictionary ?? [:]
                if data["merchantType"]as? String ?? "" == "0"{
                    AuthenCompanyMsgModel.shareInstance.refreshMsg(dict: data)
                    AuthenCompanyMsgModel.shareInstance.posChannel = UserModel.shared.posChannel
                    
                    if AuthenCompanyMsgModel.shareInstance.posChannel == "fy"{
                        let vc = AuthenCompanyFYVC()
                        vc.isUpdate = true
                        if UserModel.shared.posStatus == "1" || UserModel.shared.posStatus == "2" || UserModel.shared.posStatus == "3" || UserModel.shared.posStatus == "4"{
                            vc.isRead = true
                        }
                        self.navigationController?.pushViewController(vc, animated: true)
                    }else{
                        let vc = AuthenCompanyVC()
                        vc.isUpdate = true
                        if UserModel.shared.posStatus == "1" || UserModel.shared.posStatus == "2" || UserModel.shared.posStatus == "3" || UserModel.shared.posStatus == "4"{
                            vc.isRead = true
                        }
                        self.navigationController?.pushViewController(vc, animated: true)
                    }
                }else if data["merchantType"]as? String ?? "" == "1"{
                    AuthenMiniMsgModel.shareInstance.refreshMsg(dict: data)
                    AuthenMiniMsgModel.shareInstance.posChannel = UserModel.shared.posChannel
                    let vc = AuthenMiniVC()
                    vc.isUpdate = true
                    if UserModel.shared.posStatus == "1" || UserModel.shared.posStatus == "2" || UserModel.shared.posStatus == "3" || UserModel.shared.posStatus == "4"{
                        vc.isRead = true
                    }
                    self.navigationController?.pushViewController(vc, animated: true)
                }else if data["merchantType"]as? String ?? "" == "2"{
                    AuthenCompanyMsgModel.shareInstance.refreshMsg(dict: data)
                    AuthenCompanyMsgModel.shareInstance.posChannel = UserModel.shared.posChannel
                    let vc = AuthenGeTiVC()
                    vc.isUpdate = true
                    if UserModel.shared.posStatus == "1" || UserModel.shared.posStatus == "2" || UserModel.shared.posStatus == "3" || UserModel.shared.posStatus == "4"{
                        vc.isRead = true
                    }
                    self.navigationController?.pushViewController(vc, animated: true)
                }else{
                    let vc = AuthenTypeVC()
                    vc.isFromMine = true
                    self.navigationController?.pushViewController(vc, animated: true)
                }
            }else{
                self.presentAlertVcNoAction(title: "\(response["message"]as? String ?? "网络请求错误")", viewController: self)
            }
        }
    }
//    func sendGetMsgRequset() {
//        MCToast.mc_loading()
//        let urlString = "\(URL_authen_msg_query)?tel=\(UserModel.shared.phone)"
//        
//        WHNetworkUtil.shareManager().GET(urlString: urlString,vc:self) { responseObject in
//            DLLog(message: "\(responseObject)")
//            let dataObj = responseObject["data"]as? NSDictionary ?? [:]
//            if dataObj["merchantType"]as? String ?? "" == "1"{
//                AuthenMiniMsgModel.shareInstance.refreshMsg(dict: dataObj)
//                let vc = AuthenMiniVC()
//                vc.isUpdate = true
//                self.navigationController?.pushViewController(vc, animated: true)
//            }
//            
//        }
//    }
    func sendGetSampleImgRequest()  {
        WHNetworkUtil.shareManager().POST(urlString: URL_Get_SampleImage, parameters: nil) { responseObject in
            DLLog(message: "sendGetSampleImgRequest:\(responseObject)")
            let datadict = responseObject["data"]as? NSDictionary ?? [:]
            AuthenSampleImageModel.shareInstance.dealSampleImg(dict: datadict)
        }
    }
    func sendGetVersionRequest(){
        WHNetworkUtil.shareManager().POST(urlString: URL_Get_Appversion, parameters: nil) { response in
            DLLog(message: "sendGetVersionRequest：\(response)")
            let dataDict = response["data"]as? NSDictionary ?? [:]
            let currentVersion = Bundle.main.infoDictionary!["CFBundleShortVersionString"] as! String
            DLLog(message: "currentBuildVersion:\(currentVersion)")
            
            let iosVersionNo = dataDict["iosVersionNo"]as? String ?? ""
            let iosVersionNoString = iosVersionNo.replacingOccurrences(of: ".", with: "")
//            let currentBuildInt = currentVersionString.intValue
            let iosVersionInt = iosVersionNoString.intValue
            
            //获取app信息
            let infoDictionary : Dictionary = Bundle.main.infoDictionary!
            //版本号
            let buildVersion :String = infoDictionary ["CFBundleVersion"] as! String
            let currentBuildInt = buildVersion.intValue
            
            if dataDict["iosIfUpdate"]as? String ?? "" == "1" && iosVersionInt > currentBuildInt{
                self.presentAlertVc(confirmBtn: "确定", message: dataDict["remark"]as? String ?? "", title: "V\(dataDict["iosVersionNo"]as? String ?? "") 版本更新", cancelBtn: nil, handler: { action in
                    self.openUrl(urlString: dataDict["iosDownUrl"]as? String ?? "")
//                    exit(0)
                }, viewController: self)
            }
        }
    }
    func sendDataQueryRequest() {
        MCToast.mc_loading()
        let param = ["pageNum":"1",
                     "pageSize":"5",
                     "startTime":"\(Date().todayDate)",
                     "endTime":"\(Date().todayDate)",
                     "orderStatus":"0",
                     "type":""]
        WHNetworkUtil.shareManager().POST(urlString: "\(URL_trade_query)", parameters: param as [String:AnyObject],isNeedToast: true,vc:self) { responseObject in
            DLLog(message: "\(responseObject)")
            let dataObj = responseObject["data"]as? NSDictionary ?? [:]
            self.topVm.todayNumberVm.updateUI(dict: dataObj["obj"]as? NSDictionary ?? [:])
        }
    }
}
